package com.nami.ucenter.application.login;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import com.nami.im.network.model.enums.DownMsgErrorCode;
import com.nami.ucenter.application.convertor.UserLoginCmdToModelAssembler;
import com.nami.ucenter.domain.model.UserLoginModel;
import com.nami.ucenter.domain.port.repository.CacheUserRepository;
import com.nami.ucenter.domain.service.UserLoginDomainService;
import com.nami.ucenter.facade.login.ConnectLoginFacade;
import com.nami.ucenter.facade.login.request.command.UserLoginCmd;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class ConnectLoginFacadeImpl implements ConnectLoginFacade {

    private final UserLoginDomainService userDomainService;
    private final CacheUserRepository cacheUserDomainService;

    @Override
    public void execute(UserLoginCmd cmd) {
        TimeInterval timer = DateUtil.timer();
        // 1. 验证请求参数
        if (!cmd.validateBasic()) {
            userDomainService.sendLoginFailureResponse(cmd.getUserId(),
                cmd.getTempFingerprint(),
                cmd.getConnectId(),
                DownMsgErrorCode.REQUEST_PARAMS_ERROR);
            return;
        }
        UserLoginModel model = UserLoginCmdToModelAssembler
            .toModel(cmd);
        if (userDomainService.fillParamsAfterCheck(model)) {
            log.warn("用户登录失败，用户信息: {}-{}", model.getUserId(), model.getNick());
            return;
        }

        boolean isSuccess = cacheUserDomainService.userLoginWithLock(model);
        if (!isSuccess) {
            userDomainService.sendLoginFailureResponse(cmd.getUserId(),
                cmd.getTempFingerprint(),
                cmd.getConnectId(),
                DownMsgErrorCode.USER_LOGGED);
            log.warn("用户已登录，user:{}-{}", model.getUserId(), model.getNick());
            return;
        }

        // 发送登录成功响应
        userDomainService.publishLoginSuccEvent(model);
        log.info("[login] 用户[{}]登录成功, 设备类型==>{}, 指纹:{}, 使用{}ms",
            model.getNick(),
            cmd.getPlatform(),
            cmd.getTempFingerprint(),
            timer.interval());
    }

}
